package models.baseinfo

import javax.inject.Inject
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

import java.sql.Timestamp
import scala.concurrent.{ExecutionContext, Future}

class KDStockCodeRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)(implicit executionContext: ExecutionContext)
  extends HasDatabaseConfigProvider[JdbcProfile] {

  import dbConfig._
  import profile.api._

  private class KDStockCodeTable(tag: Tag) extends Table[KDStockCode](tag, "IMED_KDSTOCKCODE") {
    def id = column[Long]("ID", O.PrimaryKey)

    def kdFStockId = column[Int]("FStockId".toUpperCase)

    def kdFNumber = column[String]("FNumber".toUpperCase)

    def kdFName = column[String]("FName".toUpperCase)

    def kdFTHIRDSTOCKNO = column[String]("FTHIRDSTOCKNO".toUpperCase)

    def status = column[Boolean]("status".toUpperCase)

    def org = column[String]("org".toUpperCase)

    def upDate = column[Timestamp]("UP_DATE")

    def * = (id, kdFStockId, kdFNumber, kdFName, kdFTHIRDSTOCKNO, status,org, upDate)
      .<>((KDStockCode.apply _).tupled, KDStockCode.unapply)
  }

  private val stockCodeTable = TableQuery[KDStockCodeTable]

  def insert(kd: KDStockCode) = db.run {
    stockCodeTable.filter(_.kdFStockId === kd.kdFStockId).result
  }.flatMap {
    r =>
      db.run {
        if (r.nonEmpty) {
          if (kd.kdFTHIRDSTOCKNO.isEmpty) {
            stockCodeTable.filter(_.id === kd.id)
              .map(f => (f.kdFName, f.kdFNumber, f.upDate))
              .update((kd.kdFName, kd.kdFNumber, kd.upDate))
          }
          else stockCodeTable.filter(_.id === kd.id).map(f => f).update(kd)
        } else {
          stockCodeTable returning stockCodeTable.map(_.id) += kd
        }
      }
  }

  def list = db.run {
    stockCodeTable.map(f => f).result
  }

}
